package com.zhaoyizhe.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import com.zhaoyizhe.captcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    private Long TIME = (long) (5 * 60 * 1000);
    @Autowired
    private CaptchaProperties captchaProperties;
    @RequestMapping("/get")
    public void getCaptcha(HttpServletResponse response, HttpSession session) {
        ICaptcha captcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        try {
            response.setHeader("Pragma","no-cache");
            response.setContentType("image/jpeg");
            captcha.write(response.getOutputStream());
            System.out.println(captcha.getCode());
            session.setAttribute(captchaProperties.getSession().getCode(),captcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(),System.currentTimeMillis());

            response.getOutputStream().close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    @RequestMapping("/check")
    public Boolean check(String userCaptcha , HttpSession session) {
        if (!StringUtils.hasLength(userCaptcha)) {
            return false;
        }
        String sessionCode = (String) session.getAttribute(captchaProperties.getSession().getCode());
        Long sessionDate =(Long) session.getAttribute(captchaProperties.getSession().getDate());
        if (sessionCode.equalsIgnoreCase(userCaptcha) && System.currentTimeMillis() - sessionDate < TIME) {
            return true;
        }
        return false;
    }




}
